package fr.axgame;

import java.util.Random;

import fr.axgame.utils.FightReport;

public class Fight {

	private Hero hero;
	private Mob mob; // A remplacer par une liste

	public Fight(Hero hero, Mob mob) {
		this.hero = hero;
		this.mob = mob;
	}

	public Attack attack(Character attacker, Character defender) throws Exception {
		if (attacker == null || defender == null) {
			throw new Exception("Attacker or defender is null");
		}
		Attack attack = new Attack(attacker, defender);
		int degatsDeBase = (attacker.getAttack() - defender.getDefense());
		Random critical = new Random();
		int degatsPotentiels = degatsDeBase;
		if (critical.nextInt(100) < attacker.getCriticalChance()){
			degatsPotentiels = degatsDeBase * 2;
			attack.setCritical(true);
		}
		Random touche = new Random();
		int degatsReels = degatsPotentiels;
		if (touche.nextInt(100) < (defender.getDodge() - attacker.getAccuracy())){
			degatsReels = 0;
			attack.setDodge(true);
		}
		attack.setDegats(degatsReels);
		defender.setCurrentLife(defender.getCurrentLife() - degatsReels);
		return attack;
	}
	
	public FightReport simulateFight() throws Exception{
		int attacksCount = 0;
		while (hero.getCurrentLife() > 0 && mob.getCurrentLife() > 0){
			if (attacksCount % 2 == 0){
				attack(hero, mob);
			} else {
				attack(mob, hero);
			}
			attacksCount++;
		}
		boolean win;
		if (hero.getCurrentLife() > 0 && mob.getCurrentLife() <= 0){
			win = true;
		} else if (hero.getCurrentLife() <= 0 && mob.getCurrentLife() > 0){
			win = false;
		} else {
			throw new Exception("Fight error : hero life " + hero.getCurrentLife() + "hp, mob life " + mob.getCurrentLife() + "hp");
		}
		return new FightReport(attacksCount / 2 + 1, win);
	}
	
	public void reinitFight(){
		hero.setCurrentLife(hero.getMaxLife());
		mob.setCurrentLife(mob.getMaxLife());
	}

	public Hero getHero() {
		return hero;
	}

	public void setHero(Hero hero) {
		this.hero = hero;
	}

	public Mob getMob() {
		return mob;
	}

	public void setMob(Mob mob) {
		this.mob = mob;
	}
	
}
